package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取请求url
        String url = request.getRequestURL().toString();

        // 2.判断请求url中是否包含login，如果包含，证明是登录请求，放行
        if (url.contains("login")) {
            // 放行
            filterChain.doFilter(request, response);
            return; // 结束过滤器方法的执行
        }

        // 3.不是登录请求，获取请求头中的token
        String jwt = request.getHeader("token");

        // 4.判断令牌是否存在，如果不存在，返回错误结果
        if (!StringUtils.hasLength(jwt)) {
            Result result = Result.error("NOT_LOGIN");
            // 借助于FastJson工具类将对象转换成Json字符串
            String jsonString = JSONObject.toJSONString(result);
            response.getWriter().println(jsonString);
            return;
        }

        // 5.证明有令牌，解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            response.getWriter().println(JSONObject.toJSONString(Result.error("NOT_LOGIN")));
            return;
        }

        // 6.解析令牌没报错，放行
        filterChain.doFilter(request, response);
    }
}
